/** 
 * @ClassName: UserCartService 
 * @Description:
 * @author 816
 * @date 2016-10-27
 *  
 */
package com.fzrskj.cloud.free.user.service;

import com.fzrskj.cloud.free.consts.AppCode;
import com.fzrskj.cloud.free.core.enums.DicParamEnum;
import com.fzrskj.cloud.free.core.tool.CJsonTool;
import com.fzrskj.cloud.free.core.tool.CSessionTool;
import com.fzrskj.cloud.free.core.tool.CStrTool;
import com.fzrskj.cloud.free.core.utils.CloudContextUtils;
import com.fzrskj.cloud.free.dic.utils.DicParamUtils;
import com.fzrskj.cloud.free.sys.bean.SysProductView;
import com.fzrskj.cloud.free.sys.utils.SysProductUtils;
import com.fzrskj.cloud.free.user.bean.UserCart;
import com.fzrskj.cloud.free.user.bean.UserCartView;
import com.fzrskj.cloud.free.user.bean.UserDiyBean;
import com.fzrskj.cloud.free.user.utils.UserCartUtils;
import com.fzrskj.cloud.free.user.utils.UserDiyUtils;
import com.fzrskj.cloud.free.user.bean.UserAccountView;
import com.fzrskj.cloud.free.user.utils.UserAccountUtils;
import com.winiis.component.common.utils.bean.ClassUtils;
import com.winiis.component.common.utils.tool.CSysTool;
import ms.core.consts.SysErr;
import ms.core.tool.JsonTool;
import ms.core.tool.StrTool;
import ms.core.tool.XmlCodeParser;
import net.sf.json.JSONObject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserCartService {
		public String addUserCartDiy(HttpServletRequest req, HttpServletResponse resp, String p, String sid) {
		int uid = CloudContextUtils.getSession().getUID();
		JSONObject result = new JSONObject();

		//购物车信息
		String productCode= CJsonTool.getStrValue(p, "productCode", "");	//产品编号
		int applyTime=CJsonTool.getIntValue(p, "applyTime", 1);		    //购买时长
		String priceType=CJsonTool.getStrValue(p, "priceType", "");        //价格类型
		String cartType=CJsonTool.getStrValue(p, "cartType", "");          //购物车类型
		String productParam=CJsonTool.getStrValue(p, "productParam", "");  //产品参数
		int num=CJsonTool.getIntValue(p, "num", 1);                     //数量
		String businessId = CJsonTool.getStrValue(p, "businessId", "");
		if(CStrTool.isBlankStr(productCode) ||
				applyTime<=0 					||
				CStrTool.isBlankStr(priceType) 	||
				CStrTool.isBlankStr(cartType) 	||
				CStrTool.isBlankStr(productParam)){
			return XmlCodeParser.formatResultTips(false,SysErr.SYS_PARAM_ERR);
		}

		//获取产品信息
		SysProductUtils utils=new SysProductUtils();
		Map<String,Object> cdt = new HashMap<String, Object>();
		cdt.put("productCode", productCode);
		SysProductView view=utils.querySysProduct(cdt);
		if(view==null) {
			return XmlCodeParser.formatResultTips(false, AppCode.PRODUCT_NOT_EXISTS);
		}
		JSONObject configProductParam = JSONObject.fromObject(view.getProductParam());

		//虚拟主机参数验证
		JSONObject param = JSONObject.fromObject(productParam);
		//相关参数
		param.putAll(ClassUtils.copy(configProductParam, Map.class));

		UserDiyUtils diyUtils = new UserDiyUtils();
		if (!StrTool.isBlankStr(businessId)) {
			UserDiyBean diyBean = diyUtils.queryUserDiy(Integer.valueOf(businessId));
			JSONObject openInfo = JSONObject.fromObject(diyBean.getOpenInfo());
			JSONObject diyParams = openInfo.containsKey("diy_params") ? openInfo.getJSONObject("diy_params") : new JSONObject();
			diyParams.put("number", 1);
			diyParams.put("period", applyTime);
			diyParams.put("period_unit", "m".equals(priceType) ? "month" : "year");
			param.put("diy_params", diyParams);
			param.put("order_describe", openInfo.get("order_describe"));
		}

		//添加购物车
		UserCartUtils ucUtils=new UserCartUtils();
		for(int i=0;i<num;i++){
			UserCart userCart=new UserCart();
			String cartNo="Y"+new SimpleDateFormat("yyyyMMdd").format(new Date())+ CSysTool.getRandomNum(100000, 999999);
			userCart.setCartNo(cartNo);
			userCart.setApplyTime(applyTime);
			userCart.setCartType(cartType);
			userCart.setPriceType(priceType);
			userCart.setProductClass(view.getProductClass());
			userCart.setProductCode(view.getProductCode());
			userCart.setProductParam(param.toString());
			userCart.setRegType(view.getRegType());
			userCart.setUserName(CSessionTool.getAccountCloud(sid));
			userCart.setUserId(uid);
			userCart.setCartTime(new Date());
			userCart.setBusinessId(businessId);
			ucUtils.addUserCartDiy(userCart);
		}

		result.put("code", "0");
		return XmlCodeParser.formatResultData(true, SysErr.CODE_SUCCESS,result.toString());
	}

	/**
	 * 获取购物车列表
	 * @param req
	 * @param resp
	 * @param p{}
	 * @param sid
	 * @return
	 */
	public String getUserCartList(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		int uid = CloudContextUtils.getSession().getUID();
		
		UserCartUtils utils=new UserCartUtils();
		Map<String,Object> cdt = new HashMap<String, Object>();
		cdt.put("userId", uid);
		List<UserCartView> list=utils.getUserCartList(cdt);
		String code=utils.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)){
			return XmlCodeParser.formatResultTips(false, code);
		}
		
		//购物车总价格
		double totalPirce=0;
		if(list!=null && list.size()>0){
			for(UserCartView view: list){
				totalPirce+=view.getPrice();
			}
		}

		String data = String.format("{\"list\":%s,\"total\":%s,\"totalPrice\":%s}", JsonTool.listBeanToJson(list),list.size(),totalPirce);
		return XmlCodeParser.formatResultData(true, SysErr.CODE_SUCCESS, data);
	}
	
	/**
	 * 删除购物车
	 * @param req
	 * @param resp
	 * @param p{"cartNos":"cartNos"}
	 * @param sid
	 * @return
	 */
	public String delUserCart(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		int uid = CloudContextUtils.getSession().getUID();
		
		String cartNos = JsonTool.getStrValue(p, "cartNos", "");
		UserCartUtils utils=new UserCartUtils();
		int ret=utils.delUserCart(uid, cartNos);
		String code=utils.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			return XmlCodeParser.formatResultTips(false, code);
		}
		
		return XmlCodeParser.formatResultTips(ret>0, code);
	}
	
	/**
	 * 更改购物车
	 * @param req
	 * @param resp
	 * @param p{}
	 * @param sid
	 * @return
	 */
	public String uptUserCart(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		String cartNo = JsonTool.getStrValue(p, "cartNo", "");
		int applyTime=JsonTool.getIntValue(p, "applyTime", 1);
		String priceType=JsonTool.getStrValue(p, "priceType", "");
		int regType=JsonTool.getIntValue(p, "regType", -1);
		if(StrTool.isBlankStr(cartNo) || applyTime<1 || StrTool.isBlankStr(priceType)){
			return XmlCodeParser.formatResultTips(false,SysErr.SYS_PARAM_ERR);
		}
		
		Map<String,Object> values = new HashMap<String, Object>();
		values.put("applyTime", applyTime);
		values.put("priceType", priceType);
		if (regType > 0) {
			values.put("regType", regType);
		}
		Map<String,Object> cdt = new HashMap<String, Object>();
		cdt.put("cartNo", cartNo);
		
		UserCartUtils ucUtils=new UserCartUtils();
		int ret=ucUtils.modUserCart(values, cdt);
		return XmlCodeParser.formatResultTips(ret>0,ucUtils.getErrCode());
	}

	/**
	 * 修改购物车域名注册商
	 * @param req
	 * @param resp
	 * @param p{}
	 * @param sid
	 * @return
	 * add wzj by 2019-01-14
	 */
	public String uptUserCartDomainRegtype(HttpServletRequest req, HttpServletResponse resp, String p, String sid) {
		String cartNo = JsonTool.getStrValue(p, "cartNo", "");
		String regType = JsonTool.getStrValue(p, "regType", "");
		if (StrTool.isBlankStr(cartNo) || StrTool.isBlankStr(regType)) {
			return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
		}

		Map<String, Object> values = new HashMap<String, Object>();
		values.put("regType", regType);
		Map<String, Object> cdt = new HashMap<String, Object>();
		cdt.put("cartNo", cartNo);

		UserCartUtils ucUtils = new UserCartUtils();
		int ret = ucUtils.modUserCartDomainRegtype(values, cdt);
		return XmlCodeParser.formatResultTips(ret > 0, ucUtils.getErrCode());
	}

	/**
	 * 统计总价格
	 * @param req
	 * @param resp
	 * @param p{"cartNos":"cartNos"}
	 * @param sid
	 * @return
	 */
	public String countTotalPrice(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		int uid = CloudContextUtils.getSession().getUID();
		
		String cartNos = JsonTool.getStrValue(p, "cartNos", "");
		UserCartUtils ucUtils=new UserCartUtils();
		double totalPrice=ucUtils.countTotalPrice(uid, cartNos);	
		return XmlCodeParser.formatResultData(true, SysErr.CODE_SUCCESS, String.valueOf(totalPrice));
	}
	
	/**
	 * 更改购物车域名信息
	 * @param req
	 * @param resp
	 * @param p{}
	 * @param sid
	 * @return
	 */
	public String upDomainUserCart(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		String cartNo = JsonTool.getStrValue(p, "cartNo", "");
		String productParam=JsonTool.getStrValue(p, "productParam", "");
		
		if(StrTool.isBlankStr(cartNo) ||  StrTool.isBlankStr(productParam)){
			return XmlCodeParser.formatResultTips(false,SysErr.SYS_PARAM_ERR);
		}

		//检查会员实名状态
		if ("Y".equals(DicParamUtils.getParamValue(DicParamEnum.MUST_REAL_NAME.getVal()))) {
			UserAccountView userAccount = UserAccountUtils.getUserAccountView(CloudContextUtils.getSession().getUID());
			if (3 != userAccount.getIsCertified()) {
				return XmlCodeParser.formatResultTips(false, "MUST REAL NAME", "您的账号还未通过实名认证，无法下单开展新业务");
			}
		}

		Map<String,Object> values = new HashMap<String, Object>();
		values.put("productParam", productParam);
		Map<String,Object> cdt = new HashMap<String, Object>();
		cdt.put("cartNo", cartNo);
		UserCartUtils ucUtils=new UserCartUtils();
		ucUtils.upDomainUserCart(values, cdt);
		String code = ucUtils.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			return XmlCodeParser.formatResultTips(false, code);
		}
		return XmlCodeParser.formatResultTips(true,ucUtils.getErrCode());
	}
	
	/**
	 * 查询会员购物车数量
	 * @param req
	 * @param resp
	 * @param p
	 * @param sid
	 * @return
	 */
	public String queryUserCartCount(HttpServletRequest req, HttpServletResponse resp, String p, String sid){
		int uid = CSessionTool.getUidCloud(sid);
		//如果没有登录返回值为0
		if (uid <= 0) {
			String data = String.format("{\"count\":%s}",0);
			return XmlCodeParser.formatResultData(true, SysErr.CODE_SUCCESS, data);
		}
		
		String userName = CSessionTool.getAccountCloud(sid);
		UserCartUtils userCartUtils = new UserCartUtils();
		int count = userCartUtils.queryUserCartCount(userName);
		String code = userCartUtils.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)){
			String data = String.format("{\"count\":%s}",0);
			return XmlCodeParser.formatResultData(true, SysErr.CODE_SUCCESS, data);
		}
		
		String data = String.format("{\"count\":%s}",count);
		return XmlCodeParser.formatResultData(true, SysErr.CODE_SUCCESS, data);
	}
}
